package com.example.cors.service;


import com.example.cors.domain.CorsReq;
import okhttp3.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Service
public class CorsService {
    private final OkHttpClient client = new OkHttpClient();

    private static final MediaType MEDIA_JSON = MediaType.get("application/json; charset=utf-8");


    public String sendReq(CorsReq req) throws IOException {
        HttpServletRequest servletRequest = req.getReq();
        Headers.Builder builder = new Headers.Builder();
        if (req.getUseHeaders() != null) {
            req.getUseHeaders().forEach(hName-> {
                String header = servletRequest.getHeader(hName);
                if (header != null){
                    builder.add(hName,header);
                }
            });
        }
        Request.Builder reqBuilder = new Request.Builder()
                .headers(builder.build())
                .url(req.getUrl());

        if ("post".equals(req.getMethod()) || "POST".equals(req.getMethod())){
            RequestBody reqBody = RequestBody.create(req.getBody().toString(), MEDIA_JSON);
            reqBuilder.post(reqBody);
        }
        return client.newCall(reqBuilder.build()).execute().body().string();
    }



}
